package com.chance.cc.crawler.development.scripts.eol;

import com.chance.cc.crawler.core.CrawlerEnum;
import com.chance.cc.crawler.core.CrawlerRecordContext;
import com.chance.cc.crawler.core.downloader.HttpPage;
import com.chance.cc.crawler.core.pipeline.result.CrawlerData;
import com.chance.cc.crawler.core.record.CrawlerRequestRecord;
import com.chance.cc.crawler.core.script.crawler.CrawlerCommonScript;
import com.chance.cc.crawler.core.selector.Selectable;
import com.chance.cc.crawler.core.tags.crawler.CrawlerResultTags;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.chance.cc.crawler.core.CrawlerEnum.CrawlerDataType.article;
import static com.chance.cc.crawler.core.CrawlerEnum.CrawlerDataType.interaction;

public class EolNewsCrawlerScript extends CrawlerCommonScript {
    private Logger log= LoggerFactory.getLogger(EolNewsCrawlerScript.class);
    private static final String url="https://news.eol.cn/";
    @Override
    public String domain() {
        return "eolNews";
    }

    @Override
    public boolean crawlerCheck(CrawlerRequestRecord crawlerRequestRecord) {
        return true;
    }

    @Override
    public void initUrlRegulars() {
        addUrlRegular("https://news\\.eol\\.cn/yaowen/index\\S*shtml");
        addUrlRegular("https://\\S*.eol.cn/\\S*/\\d*/t\\d*_\\d*\\.shtml");
    }
    @Override
    public List<CrawlerRequestRecord> parseLinks(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        List<CrawlerRequestRecord> parsedLinks=new ArrayList<>();

        String lastUrl = httpPage.getRequest().getUrl();

        String nextPageUrl = null;
        if (lastUrl.matches("https://news\\.eol\\.cn/yaowen/index\\.shtml")){
            nextPageUrl = lastUrl.replace(".shtml","_1.shtml");
        }else {
            int currentPage = Integer.parseInt(lastUrl.substring(lastUrl.lastIndexOf("_") + 1).split("\\.")[0]);
            nextPageUrl = lastUrl.substring(0 , lastUrl.lastIndexOf("_") + 1) + (currentPage + 1) + ".html";
        }

        CrawlerRequestRecord turnPageRequest = CrawlerRequestRecord.builder()
                    .turnPageRequest(crawlerRequestRecord)
                    .recordKey(nextPageUrl)
                    .httpUrl(nextPageUrl)
                    .releaseTime(System.currentTimeMillis())
                    .build();

        parsedLinks.add(turnPageRequest);


        List<Selectable> nodes=httpPage.getHtml().xpath("//div[@class=\"list\"]").nodes();
        for(Selectable node:nodes){
            String itemUrl=node.xpath("./div[@class=\"fline\"]/a/@href").get();
            if(itemUrl!=null){
                if(itemUrl.matches("../\\S*/\\S*/\\d*/t\\d*_\\d*\\.shtml")){
                    itemUrl="https://news.eol.cn/"+itemUrl.substring(itemUrl.indexOf("/")+1);
                }else if(itemUrl.matches("./\\d*/t\\d*_\\d*\\.shtml")){
                    itemUrl="https://news.eol.cn/yaowen/"+itemUrl.substring(itemUrl.indexOf("/")+1);
                }else if(itemUrl.matches("../\\S*/\\d*/t\\d*_\\d*\\.shtml")){
                    itemUrl="https://news.eol.cn/"+itemUrl.substring(itemUrl.indexOf("/")+1);
                }
            }

            if(StringUtils.isBlank(itemUrl)){
                continue;
            }
                String pubTime = node.xpath("./div//span[@class=\"time\"]").get();
                try {
                    long releaseTime = DateUtils.parseDate(pubTime, "yyyy-MM-dd").getTime();

                    CrawlerRequestRecord itemRecord = CrawlerRequestRecord.builder()
                            .itemPageRequest(crawlerRequestRecord)
                            .recordKey(itemUrl)
                            .httpUrl(itemUrl)
                            .releaseTime(releaseTime)
                            .resultLabelTag(article)
                            .build();
                    parsedLinks.add(itemRecord);
                } catch (ParseException e) {
                    e.printStackTrace();
                }


        }


        return parsedLinks;
    }

    @Override
    public List<CrawlerData> washPage(CrawlerRequestRecord crawlerRecord, HttpPage page) {
        List<CrawlerData> crawlerDataList = new ArrayList<>();
        CrawlerResultTags crawlerResultTags = crawlerRecord.tagsCreator().resultTags();
        if (crawlerResultTags.hasDataType(article)) {
            crawlerDataList.add(washArticle(crawlerRecord, page));

        }

        if (crawlerResultTags.hasDataType(interaction)) {
            crawlerDataList.add(washInteraction(crawlerRecord, page));
        }

        return crawlerDataList;
    }

    public CrawlerData washArticle(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        Map<String,String> article = new HashMap<>();
        httpPage.getRequest().getUrl();
        try {

            List<String> texts = httpPage.getHtml().xpath("//div[@class=\"TRS_Editor\"]/p/text()").all();
            if(texts.size()==0){
                texts = httpPage.getHtml().xpath("//div[@class=\"TRS_Editor\"]/div/text()").all();
            }

            String releaseTimeStr = httpPage.getHtml().xpath("//div[@class=\"time\"]/text()").get();

            Matcher mtPubTime = Pattern.compile("\\d*[-/]\\d*[-/]\\d*").matcher(releaseTimeStr);
            String pubTime = null;
            while (mtPubTime.find()){
                pubTime = mtPubTime.group(0);
            }

            StringBuffer conents = new StringBuffer();
            for (String text : texts) {
                conents.append(text).append(" ");
            }

            String itemUrl = httpPage.getRequest().getUrl();
            String articleKey = itemUrl.substring(itemUrl.lastIndexOf("/") + 1).split("\\.")[0];

            CrawlerData crawlerData = CrawlerData.builder()
                    .data(crawlerRequestRecord, httpPage)
                    .dataId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), CrawlerEnum.CrawlerDataType.article.enumVal(), articleKey))
                    .url(itemUrl)
                    .releaseTime(DateUtils.parseDate(pubTime.trim(),"yyyy-MM-dd").getTime())
                    .addContentKV("content",conents.toString().trim())
                    .addContentKV("title",httpPage.getHtml().xpath("//div[@class=\"title\"]/text()").get().trim())
                    .addContentKV("author",httpPage.getHtml().xpath("//div[@class=\"origin\"]").get().trim())
                    .build();
            return crawlerData;
        } catch (ParseException e) {
            log.error(e.getMessage(),e);
        }
        return null;

    }

    public CrawlerData washInteraction(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {

        return null;
    }

    @Override
    public void afterExecute(CrawlerRecordContext crawlerRecordContext) {

    }
}
